﻿using System;
using System.Reflection;

using UnityConfiguration.Infrastructure;

using mpu = Microsoft.Practices.Unity;
using mpuu = Microsoft.Practices.Unity.Utility;

namespace UnityConfiguration
{
    public class Extension : TypeResolvingObject, IContainerConfigurationCommand
    {
        private string _TypeName;
        /// <summary>
        /// The type or alias for the extension to add to the container.
        /// </summary>
        public string TypeName {
            get { return _TypeName; }
            set { _TypeName = value; }
        }

        /// <summary>
        /// The type of extension to add to the container.
        /// </summary>
        public Type Type {
            get {
                if (string.IsNullOrEmpty(TypeName)) {
                    return typeof(string);
                }
                return TypeResolver.ResolveType(TypeName);
            }
        }

        /// <summary>
        /// Execute this command against the given container.
        /// </summary>
        /// <remarks>
        /// Interface implementors will implement this method to
        /// apply configuration changes to the container.</remarks>
        /// <param name="container">The <see cref="IUnityContainer"/> to configure.</param>
        // FxCop suppression: Validation done by Guard class
        public void Configure(mpu.IUnityContainer container) {
            mpuu.Guard.ArgumentNotNull(container, "container");
            ConstructorInfo ctor = Type.GetConstructor(Type.EmptyTypes);
            mpu.UnityContainerExtension instance = (mpu.UnityContainerExtension)ctor.Invoke(null);
            container.AddExtension(instance);
        }
    }
}
